#include "D3D9_PCH.h"
#include "BillboardSpriteComponent.h"

const DWORD CBillboardSpriteComponent::Vertex::FVF = D3DFVF_XYZ | D3DFVF_TEX1;

CBillboardSpriteComponent::CBillboardSpriteComponent(void)
	: m_pTex(NULL)
{
	_CreateBillboardMesh();
	D3DXCreateTextureFromFile( *g_pDevice, _T("./Resource/Arrow.png"), &m_pTex );
}


CBillboardSpriteComponent::~CBillboardSpriteComponent(void)
{
	SAFE_RELEASE( m_pMesh );
	SAFE_RELEASE( m_pTex );
}

void CBillboardSpriteComponent::_CreateBillboardMesh() {
	
	D3DXCreateMeshFVF( 2, 4, D3DXMESH_MANAGED, Vertex::FVF, *g_pDevice, &m_pMesh );

	Vertex* VertexBuffer;
	const float size = 10.f;
	m_pMesh->LockVertexBuffer( 0, (void**)&VertexBuffer );
		VertexBuffer[0].position = D3DXVECTOR3( size, size, 0 );
		VertexBuffer[1].position = D3DXVECTOR3( -size, size, 0 );
		VertexBuffer[2].position = D3DXVECTOR3( -size, -size, 0 );
		VertexBuffer[3].position = D3DXVECTOR3( size, -size, 0 );
		VertexBuffer[0].u = 1;		VertexBuffer[0].v = 0;
		VertexBuffer[1].u = 0;		VertexBuffer[1].v = 0;
		VertexBuffer[2].u = 0;		VertexBuffer[2].v = 1;
		VertexBuffer[3].u = 1;		VertexBuffer[3].v = 1;
	m_pMesh->UnlockVertexBuffer();
	VertexBuffer = 0;

	WORD* IndexBuffer;
	m_pMesh->LockIndexBuffer( 0, (void**)&IndexBuffer );
		IndexBuffer[0] = 0;
		IndexBuffer[1] = 2;
		IndexBuffer[2] = 1;

		IndexBuffer[3] = 0;
		IndexBuffer[4] = 3;
		IndexBuffer[5] = 2;
	m_pMesh->UnlockIndexBuffer();
	IndexBuffer = 0;

	DWORD* AttributeBuffer;
	m_pMesh->LockAttributeBuffer( 0, &AttributeBuffer );
		AttributeBuffer[0] = AttributeBuffer[1] = 0;
	m_pMesh->UnlockAttributeBuffer();
	AttributeBuffer = 0;
}

void CBillboardSpriteComponent::Render() const {

	_PreRender();

	if ( m_pMesh != NULL ) {
		g_pDevice->SetTexture(0, m_pTex);
		g_pDevice->SetMaterial( &m_mtrlDefault );
		m_pMesh->DrawSubset(0);
	}

	_PostRender();
}

void CBillboardSpriteComponent::_PreRender() const {

	g_pDevice->SetRenderState(D3DRS_LIGHTING, false);
		
	// use alpha from texture
	g_pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
	g_pDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);

	g_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true);
	g_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
    g_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
	g_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW );
}

void CBillboardSpriteComponent::_PostRender() const {
	
	g_pDevice->SetRenderState(D3DRS_LIGHTING,          true);
	g_pDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, false);
	g_pDevice->SetRenderState(D3DRS_POINTSCALEENABLE,  false);
	g_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE,  false);

}